<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\crm\controller;

use api\crm\model\GetCardLogModel;
use api\crm\model\UserModel;
use api\crm\model\WechatUserPointsLogModel;
use api\crm\model\ZhuanhuaModel;
use app\admin\model\CommunityModel;
use app\common\model\WechatUserModel;
use plugins\wechat\WechatPlugin;
use think\Db;
use think\Controller;
use think\Image;
use think\Request;
use think\Session;
use think\Cache;
use think\Validate;
use think\View;
use cmf\controller\RestBaseController;

class PublicController extends RestBaseController
{
    public function community()
    {
        $data = $this->request->param();
        $current_user_id = $this->getUserId();
        $current_user_info = UserModel::get($current_user_id);
        $where[] = ['company_id', '=', $current_user_info['company_id']];
        $region = json_decode(stripslashes($data['region']));
        $where[] = ['region', 'eq', json_encode($region)];
        $list = CommunityModel::where($where)
            ->order('create_at desc')
            ->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['region'] = json_decode($v['region']);
            }
        }

        $this->success('', $list);

    }


    // (暂时不用，只做备份逻辑代码) 当会员卡领取成功以后  绑定微信用户上下级关系
    public function bind_relaction()
    {
        $validate = new Validate([
            'parent_id' => 'require',
            'uid' => 'require',
        ]);
        $validate->message([
            'parent_id.require' => '请传推荐人id',
            'uid.require' => '请传被推荐人id',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $find = WechatUserModel::where('id', $data['parent_id'])->find();
        if (!$find) {
            $this->error('推荐人不存在');
        }
        $search = WechatUserModel::where('id', $data['uid'])->find();
        if (!$search) {
            $this->error('被推荐人不存在');
        }
        //开始事务
        Db::startTrans();
        try {
            $count = ZhuanhuaModel::where('parent_id', $data['parent_id'])->count();
            $depp = $count + 1;
            // 转化日志
            $log = new ZhuanhuaModel([
                'parent_id' => $data['parent_id'],
                'uid' => $data['uid'],
                'depp' => $depp
            ]);
            if (!$log->save()) {
                throw new \Exception('网络错误请稍后重试！');
            }
            // 用户表更新推荐人id
            $user = WechatUserModel::get($data['uid']);
            $user->parent_id = $data['parent_id'];
            if (!$user->save()) {
                throw new \Exception('网络错误请稍后重试！');
            }

            // 推荐用户注册会员卡得积分
            $points = Db::name('option')->where('option_name', 'user_card_register' . $user['company_id'])->value('option_value');

            if (!empty($points)) {
                // 用户积分变更
                $parent = new WechatUserModel;
                $res = $parent::where('id', $data['parent_id'])->setInc('points', $points);
                if (!$res) {
                    throw new \Exception('网络错误请稍后重试！');
                }
                // 积分日志
                $log = new WechatUserPointsLogModel;
                $log->data([
                    'user_id' => $data['parent_id'],
                    'change_points' => $points,
                    'before_points' => $find['points'],
                    'after_points' => $find['points'] + $points,
                    'create_time' => time(),
                    'update_time' => time(),
                    'remark' => '分享用户昵称为：' . $search['nickname'] . '，激活会员卡成功获得' . $points . '积分',
                ]);
                if (!$log->save()) {
                    throw new \Exception('网络错误请稍后重试！');
                }
                // 变更 会员卡 积分
                $cardInfo = GetCardLogModel::where('openid', $find['openid'])
                    ->distinct(true)
                    ->field('card_id,user_card_code')->select();

                $obj = new WechatPlugin();
                if ($cardInfo) {
                    foreach ($cardInfo as $k => $v) {
                        $obj->update_card_info([
                            'company_id' => $find['company_id'],
                            'user_id' => $find['id'],
                            'cardId' => $v['card_id'],
                            'code' => $v['user_card_code'],
                            'bonus' => $find['points'] + $points
                        ]);
                    }
                }

            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('绑定推荐关系成功！');
    }


    // 奖励说明
    public function share_description()
    {
        $data = $this->request->param();
        $sharing_of_rewards = Db::name('option')->where('option_name', 'sharing_of_rewards' . $data['company_id'])->value('option_value');
        $this->success('', $sharing_of_rewards);
    }


    public function wx_jssdk()
    {
        $data = $this->request->param();
        $jssdk = hook('get_jssdk', [
            'company_id' => $data['company_id'],
            'url' => $data['url'],
        ]);
        $user_id = WechatUserModel::where('openid', $data['openid'])->where('company_id', $data['company_id'])->value('id');

        if (empty($user_id)) {
            $this->error('', [
                'jssdk' => $jssdk,
                'user_id' => false
            ]);
        } else {
            $this->success('', [
                'jssdk' => $jssdk,
                'user_id' => $user_id
            ]);
        }


    }

    public function tiaoshi()
    {
        $user_info = WechatUserModel::where('openid', 'oRdnWwvMvP2Be4s14ItV5U89bz34')->find();

        // 推荐人推荐激活会员卡  得到  积分
        if (!empty($user_info['parent_id'])) {
            $points = Db::name('option')->where('option_name', 'user_card_register' . $user_info['company_id'])->value('option_value');
            //echo $points;die;
            if (!empty($points)) {
                $find = WechatUserModel::where('id', $user_info['parent_id'])->find();
                //dump($find);die;
                // 用户积分变更
                $parent = new WechatUserModel;
                $parent::where('id', $user_info['parent_id'])->setInc('points', $points);

                // 积分日志
                $log = new WechatUserPointsLogModel;
                $log->data([
                    'user_id' => $user_info['parent_id'],
                    'change_points' => $points,
                    'before_points' => $find['points'],
                    'after_points' => $find['points'] + $points,
                    'create_time' => time(),
                    'update_time' => time(),
                    'remark' => '分享用户昵称为：' . $user_info['nickname'] . '，激活会员卡成功获得' . $points . '积分',
                ]);

                $log->save();

                // 变更 会员卡 积分
                $cardInfo = \api\crm\model\GetCardLogModel::where('openid', $find['openid'])
                    ->distinct(true)
                    ->field('card_id,user_card_code')->select();

                $obj = new WechatPlugin();
                if ($cardInfo) {
                    foreach ($cardInfo as $k => $v) {
                        $obj->update_card_info([
                            'company_id' => $find['company_id'],
                            'user_id' => $find['id'],
                            'cardId' => $v['card_id'],
                            'code' => $v['user_card_code'],
                            'bonus' => $find['points'] + $points
                        ]);
                    }
                }

            }

            echo 11;
        }
    }

}
